package com.woniuxy.mq01;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author author
 * @Create 2023-09-28 10:35
 */
public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //服务器IP地址
        factory.setHost("192.168.80.85");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");
        //连接对象
        Connection connection = factory.newConnection();
        //信道对象
        Channel channel = connection.createChannel();
        //定义队列名
        String queue = "queuehelloworld";
        channel.queueDeclare(queue, true, false, false, null);
        //消费者，监听队列,处理消息
        //String queue,
        // boolean autoAck,     是否自动确认，实际项目都使用手动确认，入门案例自动确认
        // Consumer callback     处理消息
        channel.basicConsume(queue,true,new DefaultConsumer(channel){
            //String consumerTag,       消费的标记，一个编号
            // Envelope envelope,       信封
            // AMQP.BasicProperties properties,  消息附件属性
            // byte[] body  消息正文    paylaod
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //发送邮件
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("消费者处理消息:"+new String(body));

            }
        });
    }
}
